package com.nosnow.edu.controller.front;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.nosnow.common.utils.JwtUtils;
import com.nosnow.common.utils.R;
import com.nosnow.common.vo.CourseWebVoOrder;
import com.nosnow.edu.entity.EduCourse;
import com.nosnow.edu.entity.chapter.ChapterVo;
import com.nosnow.edu.entity.vo.front.CourseFrontVo;
import com.nosnow.edu.entity.vo.front.CourseWebVo;
import com.nosnow.edu.invoking.OrdersClient;
import com.nosnow.edu.service.EduChapterService;
import com.nosnow.edu.service.EduCourseService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * @author by bingHeng
 * @version 1.0
 * @Create 2020/5/20 20:24
 */
@RestController
@RequestMapping("/edu/front/course")
public class CourseFrontController {

    @Autowired
    private EduCourseService eduCourseService;

    @Autowired
    private EduChapterService eduChapterService;

    @Autowired
    private OrdersClient ordersClient;

    // 条件查询带分页查询课程
    @PostMapping("getFrontCourseList/{page}/{limit}")
    public R getFrontCourseList(@PathVariable long page, @PathVariable long limit, @RequestBody(required = false)CourseFrontVo courseFrontVo) {
        Page<EduCourse> pageCourse = new Page<>(page, limit);
        Map<String, Object> map = eduCourseService.getCourseFrontList(pageCourse, courseFrontVo);
        return R.ok().data(map);
    }

    // 根据课程Id，查询课程详情页信息
    @GetMapping("getFrontCourseInfo/{courseId}")
    public R getFrontCourseInfo(@PathVariable String courseId, HttpServletRequest request) {
        // 1. 根据课程Id，编写sql语句查询课程信息
        CourseWebVo courseWebVo = eduCourseService.getBaseCourseInfo(courseId);

        // 2. 根据课程Id，查询章节和小节信息
        List<ChapterVo> chapterVideoList = eduChapterService.getChapterVideoByCourseId(courseId);

        // TODO JwtUtils.getMemberIdByJwtToken(request) 如果获取不到用户信息，则提示用户登录，前端跳转到登录或者注册页面

        // 3. 远程调用订单模块：根据课程Id和用户Id查询当前课程是否已经支付过了
        boolean isBuy = ordersClient.isBuyCourse(courseId, JwtUtils.getMemberIdByJwtToken(request));

        return R.ok().data("courseWebVo", courseWebVo).data("chapterVideoList", chapterVideoList).data("isBuy", isBuy);
    }

    // 根据课程Id查询课程信息
    @PostMapping("getCourseInfoOrder/{id}")
    public CourseWebVoOrder getCourseInfoOrder(@PathVariable String id) {
        CourseWebVo baseCourseInfo = eduCourseService.getBaseCourseInfo(id);
        CourseWebVoOrder courseWebVoOrder = new CourseWebVoOrder();
        BeanUtils.copyProperties(baseCourseInfo, courseWebVoOrder);
        return courseWebVoOrder;
    }
}
